//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/1.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import SVProgressHUD
//写微博控制器
class HMComposeViewController: UIViewController {

    //懒加载控件
    private lazy var sendButton:UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width:45,height:35)
        return button
    }()
    
    //发送按钮的点击事件
    @objc private func buttonClick() {
        let accessToken = HMUserAccountViewModel.sharedHMUserAccountViewModel.userAccount?.access_token
        let text = textView.emoticonText
        
        var result = ""
        
        //遍历富文本通过文本附件获取对应表情模型
        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: []) { (info, range, _) in
            
            if let attachment = info["NSAttachment"] as? HMTextAttachment {
                //代表是图片
                let chs = attachment.emoticon?.chs
                result += chs!
            }else{
                //代表是文本
                let text = textView.attributedText.attributedSubstring(from: range).string
                result += text
            }
            print(result)
        }
        
        if pictureView.images.count > 0 {
            //发送文字加配图微博
            let firstImage = pictureView.images.first!
            NetworkTools.sharedTools.upload(accessToken: accessToken!, status: text, image: firstImage, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败！")
                    print(error)
                    return
                }
                
                //执行到此代表上传成功
                SVProgressHUD.showSuccess(withStatus: "发送成功！")
                
            })
            
        }else {
            //发送文字微博
            SVProgressHUD.show()
            NetworkTools.sharedTools.update(accessToken: accessToken!, status: text) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "网络请求异常！")
                    return
                }
                
                //执行到此，表示发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功！")
                
            }
        }

        
        
        
    }
    
    //标题
    private lazy var titleLabel:UILabel = {
        let label = UILabel(textColor:UIColor.darkGray,fontSize:16)
        if let name = HMUserAccountViewModel.sharedHMUserAccountViewModel.userAccount?.name {
            //通过富文本设置
            let result = "发微博\n" + name
            //获取指定内容的范围
            let range = (result as NSString).range(of: name)
            //创建富文本
            let attributedStr:NSMutableAttributedString = NSMutableAttributedString(string:result)
            attributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.brown], range: range)
            label.attributedText = attributedStr
        }else{
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    //文本框
    fileprivate lazy var textView:HMComposeTextView = {
        let view = HMComposeTextView()
        view.placeHolder = "开开心心，高高兴兴"
        view.font = UIFont.systemFont(ofSize: 14)
        view.delegate = self
        //开启垂直方向弹簧动画效果
        view.alwaysBounceVertical = true
        return view
    }()
    
    //toolBar
    fileprivate lazy var toolBar:HMComposeToolBar = {
        let view = HMComposeToolBar()
        return view
    }()
    
    //发送微博的配图
    fileprivate lazy var pictureView:HMComposePictureView = {
       let view = HMComposePictureView()
        return view
    }()
    
    //表情键盘
    fileprivate lazy var emoticonKeyBoard:HMEmoticonKeyBoard = {
       let view = HMEmoticonKeyBoard()
        //设置大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpUI()
        //view.backgroundColor = RandomColor()
    }

    private func setUpUI() {
        setNavUI()
        //使用通知监听键盘位置的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //监听表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonNoti(noti:)), name: NSNotification.Name(DidSelectedEmoticonNotification), object: nil)
        //监听删除按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmoticonNoti), name: NSNotification.Name(DidSelectedDeleteEmoticonNotification), object: nil)
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.left.equalTo(textView)
            make.right.equalTo(textView)
            make.bottom.equalTo(view)
            make.height.equalTo(35)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        toolBar.callBack = { [weak self] (type:HMComposeToolBarButtonType) in
            
            switch type {
            case .picture:
                print("图片")
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .add:
                print("加号")
            
            }
        }
        
        pictureView.lastCellCallBack = { [weak self] in
            //打开图片浏览器
            self?.didSelectedPicture()
            
        }
    }
    
    //监听删除按钮点击的方法
    @objc private func didSelectedDeleteEmoticonNoti() {
        //从后往前删除内容
        textView.deleteBackward()
    }
    
    //监听表情按钮点击的方法
    @objc private func didSelectedEmoticonNoti(noti:Notification) {
        guard let emoticon = noti.object as? HMEmoticon else {
            return
        }
        
        textView.insertEmoticon(emoticon: emoticon)
        //每点击一个表情就保存到最近表情数组中
        HMEmoticonTools.sharedTools.saveRecentEmoticon(emoticon: emoticon)
        //通知表示视图刷新数据
        emoticonKeyBoard.reloadRecentData()
//        //执行到此，说明通知对象不为空
//        if emoticon.type == "0" {
//            //代表是图片
//            //取到表情描述
////            let chs = emoticon.chs
////            textView.insertText(chs!)
//            //把表情描述转成富文本显示
//            //记录上一次的富文本
//            let lastAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)
//            //根据表情路径创建UIImage对象
//            let image = UIImage(named:emoticon.path!)
//            //根据image对象创建文本附件
//            let attachment = NSTextAttachment()
//            //设置图片大小
//            //获取字体高度
//            let fontHeight = textView.font?.lineHeight
//            //通过设置文本附件的bounds调整表情的显示位置
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight!, height: fontHeight!)
//            attachment.image = image
//            //根据文本附件创建符文富文本
//            let attributedStr = NSAttributedString(attachment: attachment)
//            //添加被点击的表情富文本
//            //lastAttributedString.append(attributedStr)
//            //获取文本选中的范围
//            var selectedRange = textView.selectedRange
//            //把文本被选中的范围替换为富文本
//            lastAttributedString.replaceCharacters(in: selectedRange, with: attributedStr)
//            
//            //设置富文本的字体防止表情图片大小不一,value一定要解包防止崩溃
//            lastAttributedString.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, lastAttributedString.length))
//            //设置富文本
//            textView.attributedText = lastAttributedString
//            //每次点击表情光标位置加1
//            selectedRange.location += 1
//            //设置选中范围的长度
//            selectedRange.length = 0
//            textView.selectedRange = selectedRange
//              
//        }else{
//            //emoji
//            let emoji = (emoticon.code! as NSString).emoji()
//            textView.insertText(emoji!)
//            
//        }
   }
    
    //监听键盘位置改变的方法
    @objc private func keyBoardFrameChange(noti:Notification) {
        //取到键盘的位置
        let keyBoardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //取到键盘的动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //更新约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        
        //执行约束动画
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    
    private func setNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消",target:self,action:#selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView:sendButton)
        //默认关闭交互
        navigationItem.rightBarButtonItem?.isEnabled = false
        navigationItem.titleView = titleLabel
    }
    
//    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        dismiss(animated: true, completion: nil)
//    }

    @objc private func cancelAction() {
        //失去第一响应者
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

//代理方法
extension HMComposeViewController:UITextViewDelegate {
    func textViewDidChange(_ textView:UITextView) {
        //根据有无内容改变发送按钮的状态
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    //屏幕滚动时键盘失去第一响应者
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

//处理toolBar子控件的点击事件
extension HMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    //表情的点击事件
    func didSelectedEmoticon() {
        if  textView.inputView == nil{
            //从系统键盘切换到表情键盘
            textView.inputView = emoticonKeyBoard
            //表情键盘显示icon
            toolBar.showIcon(isEmoticon: true)
            
        }else {
            //从表情键盘切换到系统键盘
            textView.inputView = nil
            //系统键盘显示icon
            toolBar.showIcon(isEmoticon: false)
        }
        
        //设置第一响应者
        textView.becomeFirstResponder()
        //刷新inputView
        textView.reloadInputViews()
    }
    
    //图片的点击事件
    func didSelectedPicture() {
        let imagePictureController = UIImagePickerController()
        //设置代理
        imagePictureController.delegate = self
        //判断是否支持传入的来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePictureController.sourceType = .camera
        }else {
            imagePictureController.sourceType = .photoLibrary
        }
        
        //判断是否支持前置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("支持前置摄像头")
        }
        
        //判断是否支持后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("支持后置摄像头")
        }
        
        //允许编辑图片
        imagePictureController.allowsEditing = true
        
        self.present(imagePictureController, animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        //取消的代理方法
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //print("info\(info)")
        //获取选中图片的原始图片
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //print("image\(image)")
        
        //获取压缩后的图片
        let scaleImage = image.scaleImage(scaleWidth: 200)
        
        pictureView.addImage(image: scaleImage)
        
        picker.dismiss(animated: true, completion: nil)
    }
    

}
